#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
# import the server implementation

sensor="bme680"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":15,"check_last_shrinking":0.9,"gpg_keyid":"","digits":5,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":"BME680","sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]


# config of bme680 sensor
# use pip install bme680 for library
meas_types=["temperature","humidity","pressure","voc"]
bbme=False
if sensor in log_conf:
  bbme=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      bbme=False
  bmqtt=False
  if "mqtt" in log_conf:
    bmqtt=True
    lcmq=log_conf['mqtt']
    mbroker=""
    if 'broker' in lcmq:
      mbroker=lcmq['broker']
    else:
      bmqtt=False
    mport=1883
    if 'port' in lcmq:
      mport=lcmq['port']  
  if bbme:
    import bme680
    for n in parameter:
      if n in log_conf[sensor]:
        parameter[n]=log_conf[sensor][n]
    if "port" in log_conf[sensor]:
      bme_port=log_conf[sensor]['port']
    else:
      bme_port=1
    if "address" in log_conf[sensor]:
      parameter["i2c"]=int(log_conf[sensor]['address'],16)
    else:
      parameter["i2c"]=0x77
    try:
      sensor=bme680.BME680(i2c_addr=parameter["i2c"])
    except:
      bbme=False
    else:
      sensor.set_humidity_oversample(bme680.OS_2X)
      sensor.set_temperature_oversample(bme680.OS_2X)
      sensor.set_pressure_oversample(bme680.OS_2X)
      sensor.set_filter(bme680.FILTER_SIZE_3)
      sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)
      sensor.set_gas_heater_temperature(320)
      sensor.set_gas_heater_duration(150)
      sensor.select_gas_heater_profile(0)
      bme_sigma=3
      if "sigma" in log_conf[sensor]:
        parameter["sigma"]=int(log_conf[sensor]['sigma'])
        if parameter["sigma"] < 1:
          parameter["sigma"]=1
      partemp=parameter
      partemp["var_name"]="temperature"
      bme_temp=meas_data(partemp)
      parhum=parameter
      parhum["var_name"]="humidity"
      bme_hum=meas_data(parhum)
      parpress=parameter
      parpress["var_name"]="pressure"
      bme_press=meas_data(parpress)
      parvoc=parameter
      parvoc["var_name"]="voc"
      bme_voc=meas_data(parpress)

      if ("mqtt" in log_conf[sensor]) and bmqtt:
        bme_temp.set_mqtt(broker=mbroker,port=mport)
        bme_hum.set_mqtt(broker=mbroker,port=mport)
        bme_press.set_mqtt(broker=mbroker,port=mport)
      if "sqlserver" in log_conf:
        hostname="banana"
        if "host" in log_conf['sqlserver']:
	      hostname=log_conf['sqlserver']['host']
        port=24048
        if "port" in log_conf['sqlserver']:
	      port=int(log_conf['sqlserver']['port'])
        bme_temp.set_sql(host=hostname,port=port)
        bme_hum.set_sql(host=hostname,port=port)
        bme_press.set_sql(host=hostname,port=port)
        bme_voc.set_sql(host=hostname,port=port)
      if "opensensemap" in log_conf[sensor]:
        osm=log_conf['bme680']['opensensemap']
        if "sensebox_id" in osm:
          sid=osm['sensebox_id']
          if "sensors" in osm:
            if "temperature" in osm['sensors']:
              bme_temp.set_sensebox(sid,osm['sensors']['temperature'])
            if "humidity" in osm['sensors']:
              bme_hum.set_sensebox(sid,osm['sensors']['humidity'])
            if "pressure" in osm['sensors']:
              bme_press.set_sensebox(sid,osm['sensors']['pressure'])
            if "voc" in osm['sensors']:
              bme_voc.set_sensebox(sid,osm['sensors']['voc'])
          


if bbme:
  while True:
  
  # read bme280 (temperature, humidity, pressure)
    if sensor.get_sensor_data():
      bme_temp.append(sensor.data.temperature)
      bme_hum.append(sensor.data.humidity)
      bme_press.append(sensor.data.pressure)
#      print(sensor.data.temperature)
      if sensor.data.heat_stable:
        bme_voc.append(sensor.data.gas_resistance)
#        print(sensor.data.gas_resistance)
    time.sleep(parameter['wait'])


# close the client
print("done")


